package com.cloud.base.thread.atomic;

import java.util.concurrent.atomic.AtomicInteger;

public class AtoLock {

    public AtomicInteger atomicInteger = new AtomicInteger(0);

    //获取锁的线程
    private Thread currentThread = null;

    //重入次数
    private int size = 0;

    public void lock() throws Exception {
        for (; ; ) {
            if (Thread.currentThread() == currentThread) {
                size = size + 1;

            } else {
                if (atomicInteger.compareAndSet(0, 1)) {
                    currentThread = Thread.currentThread();
                    size = size + 1;
                    return;
                }
            }

            //防止cpu标高
            Thread.sleep(50);
        }
    }

    public void unLock() {

        if (Thread.currentThread() == currentThread) {
            size = size - 1;
            if (size == 0) {
                if (atomicInteger.compareAndSet(1, 0)) {
                    currentThread = null;
                    return;
                }
            }
        }
    }
}
